package com.cqeec.bootdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cqeec.bootdemo.common.BaseContext;
import com.cqeec.bootdemo.common.R;
import com.cqeec.bootdemo.entity.AddressBook;
import com.cqeec.bootdemo.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    // 新增
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success("新增成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        //只能获取当前用户的地址
        Long currentId = BaseContext.getCurrentId();
        // 构造查询条件
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(currentId!=null,AddressBook::getUserId, currentId);
        return R.success(addressBookService.list(queryWrapper));
    }

    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook) {
        //is_default = 1 设置为默认地址; 0 不是默认地址
        //获取当前用户的id
        Long currentId = BaseContext.getCurrentId();
        //将当前id小的地址设置为非默认地址设为0
        LambdaUpdateWrapper<AddressBook> Wrapper = new LambdaUpdateWrapper<>();
        Wrapper.set(AddressBook::getIsDefault, 0).eq(AddressBook::getUserId, currentId);
        addressBookService.update(Wrapper);
        //设置用户点的地址为1
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    //地址管理修改，删除

    //修改
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
    //数据回显
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id) {
        return R.success(addressBookService.getById(id));
    }

    //删除
    @DeleteMapping
    public R<String> delete(Long ids){
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }

    //获取默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        return R.success(addressBook);
    }
}
